using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading.Tasks;

namespace ImageResize
{
    [Icon("pack://application:,,,/ImageResize;component/Resources/Icon.png")]
    [Designer("ImageResize.Designer.ImageResizeServerCommandDesigner, ImageResize")]
    public class ImageResizeServerCommand : Command, ICommandExecutableInServerSideAsync
    {
        [FormulaProperty]
        [DisplayName("原始图片文件路径")]
        public object SourcePath { get; set; }

        [FormulaProperty]
        [DisplayName("处理后的图片文件路径")]
        public object TargetPath { get; set; }

        [FormulaProperty]
        [DisplayName("最大宽度")]
        [Description("留空或设置为-1，表示维持图片比例，仅控制最大高度")]
        public object MaxWidth { get; set; }

        [FormulaProperty]
        [DisplayName("最大高度")]
        [Description("留空或设置为-1，表示维持图片比例，仅控制最大宽度")]
        public object MaxHeight { get; set; }

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var sourcePath = (await dataContext.EvaluateFormulaAsync(SourcePath)).ToString();
            var targetPath = (await dataContext.EvaluateFormulaAsync(TargetPath)).ToString();
            float width = parsePx((await dataContext.EvaluateFormulaAsync(MaxWidth)));
            float height = parsePx((await dataContext.EvaluateFormulaAsync(MaxHeight)));

            try
            {
                if (!File.Exists(sourcePath))
                {
                    throw new FileNotFoundException("原始图片文件不存在：" + sourcePath);
                }

                Image originalImage = Image.FromFile(sourcePath);

                if (width <= 0)
                {
                    width = originalImage.Width * (height / originalImage.Height);
                }

                if (height <= 0)
                {
                    height = originalImage.Height * (width / originalImage.Width);
                }

                Image resizedImage = ImageResizer.ResizeImage(originalImage, (int)width, (int)height);

                ImageResizer.SaveImage(resizedImage, targetPath, parseExt(targetPath));

                originalImage.Dispose();
                resizedImage.Dispose();

                return new ExecuteResult();
            }
            catch (Exception ex)
            {
                dataContext.Log.AppendLine("ImageResizeServerCommand Error: " + ex.ToString());
                throw;
            }

        }

        private ImageFormat parseExt(string path)
        {

            string ext = Path.GetExtension(path).ToLower();

            switch (ext)
            {

                case ".jpg":
                case ".jpeg":
                    {

                        return ImageFormat.Jpeg;
                    }
                case ".png":
                    {
                        return ImageFormat.Png;
                    }
                case ".gif":
                    {
                        return ImageFormat.Gif;
                    }
                case ".bmp":
                    {
                        return ImageFormat.Bmp;
                    }
                default:
                    {
                        throw new InvalidCastException("输出的图片格式（后缀）仅支持jpg、jpeg、png、git和bmp。文件路径：" + path);
                    }

            }
        }
        private float parsePx(object value)
        {

            if (value == null)
            {
                return -1;
            }

            string valueStr = value.ToString().ToLower().Trim().Replace("px", "");

            float px = -1;

            float.TryParse(valueStr, out px);

            return px;
        }


        public override string ToString()
        {
            return "图片缩放";
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }
    }
}
